<template>
  <div>
    <div class="content">{{ $t('km.content') }}</div>
    <div class="file-upload">
      <el-upload
        :action="uploadUrl"
        :data="uploadHeaders"
        name="upload"
        accept=".doc,.docx,.xls,.xlsx"
        :on-preview="handlePreview"
        :with-credentials="true"
        :on-success="handleSuccess"
        :before-upload="beforeUploadfile"
        :on-remove="handleRemove"
        :default-file-list="fileList"
      >
        <em class="add-file">{{ $t('km.addFile') }}</em>
        {{ $t('km.fileDescription') }}
      </el-upload>
    </div>
    <div class="quill">
      <!--<div id="km_editor_menu"></div>-->
      <div :id="editorId"></div>
      <!--<quill-editor ref="editor" :editdata="editdata" @submitContent="submitContent"></quill-editor>-->
    </div>
    <div class="attachment-upload">
      <el-form label-position="right" :rules="rules" ref="form" :model="form">
        <el-form-item :label="$t('km.knowledgeValidity')" prop="validityPeriodType">
          <el-select v-model="form.validityPeriodType" :placeholder="$t('public.pleasePick')" @change="validityChange">
            <el-option v-for="item in validityOption" :label="item.label" :value="item.value" :key="item.value">
            </el-option>
          </el-select>
          <el-date-picker
            v-if="form.validityPeriodType === 'custom'"
            v-model="form.validityPeriod"
            size="mini"
            style="margin-left: 24px"
            type="datetimerange"
            :placeholder="$t('public.timeRanges')"
            @change="validTimeChange"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('km.uploadAttachment')" prop="">
          <el-button
            type="text"
            class="iconfont icon-fujian"
            :id="this.pluloadId"
            :disabled="progressUi.show"
          ></el-button
          ><span class="upload-size">{{ $t('km.attachmentDescription2') }}</span>
          <div>
            <template v-if="form.kmFile.length">
              <div v-for="(file, index) in form.kmFile" :key="index" class="fujian-div">
                <a :href="km.getKmUrl(file)" target="_blank" :download="file.name" class="text-color">{{
                  file.name
                }}</a>
                <!-- <a @click="onSave(km.getKmUrl(file), file.name)" target="_blank" class="text-color">{{file.name}}</a> -->
                <span class="delete" @click="deleteFile(file.id, index)">
                  <i class="el-icon-close"></i>
                </span>
                <!-- <el-button @click="deleteFile(file.id, index)" :disabled="disabled">{{$t('public.delete')}}</el-button> -->
              </div>
            </template>
            <div class="process-ui" v-if="progressUi.show">
              <span>{{ progressUi.fileName }}</span>
              <el-progress
                :text-inside="true"
                :stroke-width="18"
                :percentage="progressUi.percent"
                :status="progressUi.type"
              ></el-progress>
            </div>
          </div>
          <input type="hidden" v-model.trim="form.kmFile" />
        </el-form-item>
      </el-form>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      modal-append-to-body
      lock-scroll
      :title="$t('km.preview')"
      :visible.sync="editorDialog.isShow"
      width="800px"
    >
      <div v-html="editorDialog.content" class="editor-preview" @click="superAClickFun"></div>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      modal-append-to-body
      lock-scroll
      :title="$t('km.videoTitle')"
      :visible.sync="videoShow"
      width="800px"
    >
      <el-button type="primary" :id="videoPluloadId">{{ $t('km.videoBtn') }}</el-button>
      <div class="process-ui" v-if="progressVideo.show">
        <span>{{ progressVideo.fileName }}</span>
          <el-progress
            :text-inside="true"
            :stroke-width="18"
            :percentage="progressVideo.percent"
            :status="progressVideo.type"
          ></el-progress>
        </div>
      <div class="instructions" v-html="$t('km.videoTip')" v-once></div>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      modal-append-to-body
      lock-scroll
      :title="$t('km.fileTitle')"
      :visible.sync="fileShow"
      width="800px"
    >
      <el-button type="primary" :id="this.filePluloadId">{{ $t('km.fileBtn') }}</el-button>
      <div class="process-ui" v-if="progressVideo.show">
        <span>{{ progressVideo.fileName }}</span>
          <el-progress
            :text-inside="true"
            :stroke-width="18"
            :percentage="progressVideo.percent"
            :status="progressVideo.type"
          ></el-progress>
        </div>
      <div class="instructions" v-html="$t('km.fileTip')" v-once></div>
    </el-dialog>
  </div>
</template>
<script>
//  import quillEditor from '@/components/business-modules/km/km-detail/QuillEditor.vue'
import {
  uploadTo7moorKmDomain,
  uploadTo7moorKmImgDomain,
  PasteImguploadTo7moorKmDomain,
  qiniu7moorKmDomain
} from '@/utils/qiniuUtils'
import { getCurrentDate, filterXSS } from '@/utils/m7Utils'
import Editor from 'wangeditor'
// import { saveAs } from 'file-saver'
import * as uuid from 'uuid'
import { km } from '@/utils/cosUrl'
import { getFormatDateTime } from '@/utils/m7Utils'
export default {
  name: 'QuillPublic',
  props: {
    attachs: {
      type: Array,
      default: function () {
        return []
      }
    },
    cacheItem: {
      type: Object,
      default: function () {
        return {}
      }
    },
    itemId: String,
    KmType: String
  },
  data() {
    let validate1 = (rule, value, callback) => {
      if (value.length === 0 || value === undefined) {
        callback(new Error(this.$t('validate.required')))
      } else {
        callback()
      }
    }
    return {
      editorId: 'eidtor_' + uuid.v1(),
      pluloadId: 'pluload_' + uuid.v1(),
      imgPluloadId: 'imgPluload_' + uuid.v1(),
      videoPluloadId: 'videoPluload_' + uuid.v1(),
      filePluloadId: 'filePluloadId' + uuid.v1(),
      uploadUrl: '/kmUpload',
      uploadHeaders: {
        type: 'undefined',
        module: '',
        sessionId: this.$store.state.session.sessionId
      },
      subContent: {},
      wEditor: {},
      form: {
        kmFile: this.attachs || [],
        validityPeriod: [],
        validityPeriodType: 'permanent'
      },
      rules: {
        kmFile: [{ validator: validate1, required: true, trigger: 'change' }],
        validityPeriodType: [{ required: true, message: this.$t('km.knowledgeValidityTip'), trigger: 'change' }]
      },
      progressUi: {
        show: false,
        percent: 0,
        type: 'success',
        fileName: '',
        disabled: false
      },
      progressVideo: {
        show: false,
        percent: 0,
        type: 'success',
        fileName: '',
        disabled: false
      },
      fileList: {},
      m7uploaders: [],
      editorDialog: {
        isShow: false,
        content: ''
      },
      isUseQiniu: this.$store.state.isUseQiniu,
      km,
      validityOption: [
        {
          label: '永久有效',
          value: 'permanent'
        },
        {
          label: '无效',
          value: 'invalid'
        },
        {
          label: '自定义有效期',
          value: 'custom'
        }
      ],
      videoShow: false,
      fileShow: false,
      uploadType: ['video', 'file'],
      maxVideOrFileSize: '50mb'
    }
  },
  watch: {},
  computed: {
    attachmentMaxSize() {
      return this.$store.state.attachmentMaxSize
    }
  },
  methods: {
    checkForm() {
      // 表单校验
      let status = false
      let customTime = true
      this.$refs.form.validate((valid) => {
        if (valid) {
          status = true
          // 选择了有效期但是清空了有效时间
          if (
            this.form.validityPeriodType === 'custom' &&
            (!this.form.validityPeriod || !this.form.validityPeriod.length)
          ) {
            customTime = false
          }
        }
      })
      return { status, customTime }
    },
    validityChange(val) {
      if (val === 'custom') {
        this.form.validityPeriod = [
          getFormatDateTime(new Date()),
          getFormatDateTime(new Date()).split(' ')[0] + ' 23:59:59'
        ]
      }
    },
    validTimeChange(val) {
      if (val && val.length) {
        const end = val[1].getTime()
        const start = val[0].getTime()
        if (end - start < 1 * 60 * 1000) {
          this.$message.error(this.$t('km.timeTip'))
          this.form.validityPeriod = [
            getFormatDateTime(new Date()),
            getFormatDateTime(new Date()).split(' ')[0] + ' 23:59:59'
          ]
        }
      }
    },
    onSave(...arg) {
      console.log(arg)
      saveAs(...arg)
    },
    handlePreview() {},
    handleRemove() {},
    getSuffix(url) {
      const arr = url.split('.') || []
      return arr[arr.length - 1]
    },
    // 预览
    preview() {
      this.editorDialog.isShow = true
      this.editorDialog.content = this.wEditor.txt.html()
      // table加border
      if (
        new RegExp('<table border="0" width="100%" cellpadding="0" cellspacing="0">').test(this.editorDialog.content)
      ) {
        this.editorDialog.content = this.editorDialog.content.replace(
          /<table border="0" width="100%" cellpadding="0" cellspacing="0">/g,
          '<table style="width:100%;" cellpadding="2" cellspacing="0" border="1" bordercolor="#262626">'
        )
      }
    },
    superAClickFun(e) {
      e.preventDefault()
      this.$nextTick(() => {
        if (e.target.nodeName.toLowerCase() === 'a') {
          let dom = e.target
          let domUrl = dom.getAttribute('href')
          try {
            window.open(domUrl, '_blank')
          } catch (e) {
            this.$message.error(this.$t('webchat.urlError'))
          }
        }
      })
    },
    pasteImg(evnet) {
      let ele = evnet.clipboardData.items || []
      let account = this.$store.state.session.user.account
      let that = this
      for (let i = 0; i < ele.length; ++i) {
        if (ele.length === 1 && ele[i].kind === 'file' && ele[i].type.indexOf('image/') !== -1) {
          let blob = ele[i].getAsFile()
          let filename = 'clipboard' + new Date().getTime() + '.png'
          let uploadProgress = function (up, file) {}
          const key = km.getUploadKey(_, { name: filename })
          let fileUploaded = function (up) {
            const sourceLink = km.getFileKey({ up, isLink: true }) // 获取上传成功后的文件的Url
            // that.wEditor.txt.append('<img src="' + sourceLink + '" alt="">')
            // 改为图片在光标出插入
            that.wEditor.cmd.do('insertHtml', filterXSS('<img src="' + sourceLink + '" style="max-width:100%;"/>'))
            //              that.sendChatMsg.content = sourceLink
            //              that.handleSubmit({}, 'image')
            //              that.uploaded.uploadImg = false
            that.subContent.content = that.wEditor.txt.html()
          }
          PasteImguploadTo7moorKmDomain(
            this.$store.state.session.user._id,
            blob,
            filename,
            uploadProgress,
            fileUploaded,
            key
          )
        }
      }
    },
    beforeUploadfile(file) {
      let arr = file.name.split('.')
      let arrType = ['doc', 'docx', 'xls', 'xlsx']
      if (arrType.indexOf(arr[arr.length - 1]) !== -1) {
        // v22.2 知识库正文添加文件限制调整为5MB
        if (file.size > 5 * 1024 * 1024) {
          this.$message.error(this.$t('km.attachSizeOverLimit2'))
          return false
        } else {
          return true
        }
      } else {
        this.$message.error(this.$t('km.uploadFileWrong'))
        return false
      }
    },
    handleSuccess(response, file, fileList) {
      let split = response.filePath.split('/')
      let length = split.length - 1 // 线上环境不能写死2，而是最后一级
      let obj = {
        fileName: split[length],
        trueName: response.fileName
      }
      let loading = this.$loading({ fullscreen: true, text: this.$t('km.loading') })
      this.$store.dispatch('uploadDoc', obj).then((val) => {
        loading.close()
        let uploadDoc = this.$store.state.km.uploadDoc
        if (uploadDoc) {
          this.subContent.fileId = uploadDoc.fileId
          this.subContent.content = uploadDoc.html
          this.wEditor.txt.html(filterXSS(uploadDoc.html, true))
        }
      })
    },
    submitContent() {
      let attachs = {}
      let kmFiles = this.form.kmFile || []
      for (let i = 0; i < kmFiles.length; i++) {
        let item = kmFiles[i]
        km.getAttach(attachs, item)
      }
      let data = {
        content: this.subContent,
        attachs: attachs,
        validityPeriodType: this.form.validityPeriodType,
        validityPeriod: this.form.validityPeriod
      }
      return data
    },
    fetchData({ content, attachs, validityPeriodType, validityPeriod }) {
      this.form.kmFile = attachs || []
      let self = this
      self.wEditor.txt.html(filterXSS(content, true))
      this.subContent.content = content
      this.form.validityPeriodType = validityPeriodType
      this.form.validityPeriod = validityPeriod
    },
    initUploadKmFile(ev) {
      let account = this.$store.state.session.user.account
      let that = this
      let filters = {}
      let fileAdded = function (up, files) {
        console.log('fileAdd')
      }
      let beforeUpload = function (up, file) {
        that.progressUi.show = true
        that.progressUi.percent = 0
        that.progressUi.fileName = file.name
        console.log('beforeUpload')
      }
      let uploadProgress = function (up, file) {
        that.progressUi.percent = file.percent
        console.log('uploadProgress')
      }
      let uploadComplete = function () {
        that.progressUi.show = false
        console.log('uploadComplete')
      }
      let fileUploaded = function (up, file, info) {
        let obj = {
          name: file.name,
          id: km.getFileKey({ up, file })
        }
        if (that.form.kmFile) {
          that.form.kmFile.push(obj)
        } else {
          that.form.kmFile = []
          that.form.kmFile.push(obj)
        }
      }
      let error = function (up, err, errTip) {
        if (err.code === -600) {
          that.$message.error(that.$t('km.attachmentMaxDescription'))
        }
        console.log('uploadError ' + errTip)
      }
      this.m7uploaders.push(
        uploadTo7moorKmDomain(
          this.$store.state.session.user._id,
          this.pluloadId,
          filters,
          fileAdded,
          beforeUpload,
          uploadProgress,
          uploadComplete,
          fileUploaded,
          error,
          km.getUploadKey,
          this.attachmentMaxSize
        )
      )
    },
    initUploadImageFile() {
      let account = this.$store.state.session.user.account
      let self = this
      let fileAdded = function (up, files) {
        console.log('fileAdd')
      }
      let beforeUpload = function (up, file) {
        console.log('beforeUpload1')
      }
      let uploadProgress = function (up, file) {
        console.log('uploadProgress1')
      }
      let uploadComplete = function (up, file) {
        console.log('uploadComplete1')
      }
      let fileUploaded = function (up, file, info) {
        const sourceLink = km.getFileKey({ up, info, file, isLink: true }) // 获取上传成功后的文件的Url
        if (!self.wEditor.txt.html()) {
          self.wEditor.txt.html('')
        }
        // self.wEditor.txt.append('<img src="' + sourceLink + '" alt="">')
        // 改为图片在光标出插入
        self.wEditor.cmd.do('insertHtml', filterXSS('<img src="' + sourceLink + '" style="max-width:100%;"/>'))
        self.subContent.content = self.wEditor.txt.html()
      }
      let error = function (up, err, errTip) {
        if (errTip) {
          self.$message.error(errTip)
        }
        console.log('uploadError ' + errTip)
      }
      let filters = {
        mime_types: [{ title: 'Image files', extensions: 'jpg,jpeg,gif,png,bmp' }]
      }
      this.m7uploaders.push(
        uploadTo7moorKmImgDomain(
          this.$store.state.session.user._id,
          this.imgPluloadId,
          filters,
          fileAdded,
          beforeUpload,
          uploadProgress,
          uploadComplete,
          fileUploaded,
          error,
          km.getUploadKey
        )
      )
    },
    deleteFile(fileId, index) {
      let file = this.form.kmFile[index]
      let restAttach = {}
      this.form.kmFile.forEach((item) => {
        if (item.id !== file.id) {
          km.getAttach(restAttach, item)
        }
      })
      let data = {
        _id: this.itemId,
        attachs: restAttach,
        delId: file.id,
        kmType: this.KmType
      }
      let preAtachs = this.cacheItem.attachs || {}
      if (preAtachs[file.id]) {
        data.delFiles = [file.name]
      }
      this.$store.dispatch('delAttach', data).then((res) => {
        this.form.kmFile.splice(index, 1)
      })
    },
    pauseVideo() { // 暂停富文本里的视频播放
      const video = document.getElementsByTagName('video')[0]
      if (video) {
        video.pause()
      }
    },
    initEditor() {
      this.wEditor = new Editor('#' + this.editorId)
      this.wEditor.config.menus = [
        'head', // 标题
        'bold', // 粗体
        'fontSize', // 字号
        'fontName', // 字体
        'italic', // 斜体
        'underline', // 下划线
        'strikeThrough', // 删除线
        'foreColor', // 文字颜色
        'backColor', // 背景颜色
        'link', // 插入链接
        'list', // 列表
        'justify', // 对齐方式
        //          'quote',  // 引用
        //          'emoticon',  // 表情
        'table', // 表格
        // 'code',  // 插入代码
        'undo', // 撤销
        'redo' // 重复
      ]
      // 粘贴，自定义过滤
      this.wEditor.config.pasteTextHandle = filterXSS
      this.wEditor.config.fontNames = [
        '微软雅黑',
        '宋体',
        '新宋体',
        '仿宋',
        '楷体',
        '黑体',
        'Arial',
        'Arial Black',
        'Times New Roman',
        'Courier New',
        'Tahoma',
        'Verdana'
      ]
      this.wEditor.config.onchange = (html) => {
        //         html 即变化之后的内容
        //          this.mailSignatureClone.content = this.wEditor.txt.html()
        this.subContent.content = this.wEditor.txt.html()
        if (
          new RegExp('<table border="0" width="100%" cellpadding="0" cellspacing="0">').test(this.subContent.content)
        ) {
          this.subContent.content = this.subContent.content.replace(
            /<table border="0" width="100%" cellpadding="0" cellspacing="0">/g,
            '<table style="width:100%;" cellpadding="2" cellspacing="0" border="1" bordercolor="#262626">'
          )
        }
      }
      this.wEditor.config.zIndex = 100
      let lang = window.langJson || {}
      let editLang = lang.wangeditor
      this.wEditor.config.lang = editLang
      this.wEditor.create()
      let div = document.createElement('div')
      div.className = 'w-e-menu'
      div.style.cssText = 'z-index:101;'
      let span = document.createElement('i')
      span.className = 'w-e-icon-image'
      span.id = this.imgPluloadId
      div.appendChild(span)
      // document.getElementsByClassName('w-e-toolbar')[0].appendChild(div)
      document.querySelector('#' + this.editorId + ' .w-e-toolbar').appendChild(div)
      this.initUploadImageFile()
      let self = this
      // document.getElementsByClassName('w-e-text')[0].addEventListener('paste', self.pasteImg)
      document.querySelector('#' + this.editorId + ' .w-e-text').addEventListener('paste', self.pasteImg)
      // 上传视频、文件
      this.uploadType.forEach((item) => {
        let div = document.createElement('div')
        div.className = 'w-e-menu'
        div.style.cssText = 'z-index:101;'
        let span = document.createElement('i')
        span.className = item === 'video' ? 'w-e-icon-play' : 'iconfont icon-wenjian1'
        span.style.fontSize = '12px'
        div.appendChild(span)
        div.onclick = () => {
          if (item === 'video') {
            this.videoShow = true
          } else {
            this.fileShow = true
          }
          setTimeout(() => {
            this.initUploadVideoFile(item === 'video' ? this.videoPluloadId : this.filePluloadId)
          })
        }
        document.querySelector('#' + this.editorId + ' .w-e-toolbar').appendChild(div)
      })
    },
    initUploadVideoFile(id) {
      let account = this.$store.state.session.user.account
      let that = this
      let filters = {}
      let fileAdded = function (up, files) {
        console.log('fileAdd')
      }
      let beforeUpload = function (up, file) {
        that.progressVideo.show = true
        that.progressVideo.percent = 0
        that.progressVideo.fileName = file.name
        console.log('beforeUpload')
      }
      let uploadProgress = function (up, file) {
        that.progressVideo.percent = file.percent
        console.log('uploadProgress')
      }
      let uploadComplete = function () {
        that.progressVideo.show = false
        console.log('uploadComplete')
      }
      let fileUploaded = function (up, file, info) {
        const sourceLink = km.getFileKey({ up, info, file, isLink: true }) // 获取上传成功后的文件的Url
        if (!that.wEditor.txt.html()) {
          that.wEditor.txt.html('')
        }
        if (id === that.videoPluloadId) { // 视频
          that.wEditor.txt.html(that.wEditor.txt.html() + '<br>')
        }
        if (id === that.videoPluloadId) {
          const type = file.name && file.name.indexOf('.') > -1 && file.name.split('.')[1] || ''
          if (type === '3gp') {
            that.wEditor.cmd.do('insertHtml', filterXSS(`<a href="${sourceLink}" download="${file.name}" target="_blank" style="text-decoration: none">${file.name}</a>`))
          } else {
            that.wEditor.cmd.do('insertHtml', filterXSS('<p><video controls src="' + sourceLink + '" muted style="max-width:100%;" /><br /></p>')) 
          }
          that.videoShow = false
        } else if (id === that.filePluloadId) {
          that.wEditor.cmd.do('insertHtml', filterXSS(`<a href="${sourceLink}" download="${file.name}" target="_blank">${file.name}</a>`))
          that.fileShow = false
        }
        that.subContent.content = that.wEditor.txt.html()
        that.wEditor.selection.moveCursor(that.wEditor.$textElem.elems[0],false);
      }
      let error = function (up, err, errTip) {
        if (err.code === -600) {
          that.$message.error(that.$t('km.attachmentMaxDescription'))
        }
        if (err.code === -601) {
          that.$message.error(errTip)
        }
        console.log('uploadError ' + errTip, err)
      }
      if (id === that.videoPluloadId) {
        filters = {
          mime_types: [{ title: 'video', extensions: 'mp4,3gp' }]
        }
      } else {
        filters = {
          mime_types: [{ title: 'files', extensions: 'docx,doc,xlsx,xls,pdf,pptx,txt' }]
        }
      }
      this.m7uploaders.push(
        uploadTo7moorKmDomain(
          this.$store.state.session.user._id,
          id,
          filters,
          fileAdded,
          beforeUpload,
          uploadProgress,
          uploadComplete,
          fileUploaded,
          error,
          km.getUploadKey,
          this.maxVideOrFileSize
        )
      )
    },
  },
  create() {},
  mounted() {
    this.initUploadKmFile()
    this.initEditor()
  },
  beforeDestroy() {
    this.m7uploaders.forEach((uploader) => {
      uploader && uploader.destroy && uploader.destroy()
    })
  },
  components: {
    //      quillEditor,
    Editor
  }
}
</script>
<style lang="stylus" scoped>
@import "../../../../assets/common.styl";
/deep/.w-e-text
  a
    font-size: normal !important
/deep/.w-e-text-container p
  font-size 12px !important
.instructions
  clear both
  font-size 12px
  line-height 22px
  color $c-prompt
  margin-top 16px
.text-color
  color $cf-gray0
  vertical-align middle
.fujian-div
  display inline-block
  background-color #d1f6f8
  line-height normal
  padding 5px
  margin-right 10px
  height 20px
  font-size 14px
  vertical-align top
.delete
  color $c-main
  padding-left 10px
  vertical-align middle
.content
  color $cf-gray1
  padding-bottom 5px
.file-upload
  .el-upload
    color $cf-gray3
    width auto
    .add-file
      font-style normal
      color $c-main
.quill
  margin 10px 0 10px
.attachment-upload
  margin-bottom 30px
  .icon-dakailianjie
    color $c-main
    padding-left 15px
.upload-size
  color $cf-gray3
  font-size 12px
.quill
  color $cf-gray0
.editor-preview
  min-height 200px
  max-height 60vh
  overflow-y auto
</style>
